package XML与JSON.使用SAX;

import java.util.ArrayList;
import java.util.List;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class MyHandler extends DefaultHandler {

    private List<User> users = new ArrayList<>();
    private User user;
    
    private boolean bue = false;

    private boolean bfn = false;
    private boolean bln = false;
    private boolean boc = false;

    @Override
    public void startElement(String uri, String localName,String qName, Attributes attributes) throws SAXException {
   	 //String localName:在对象字段上添加@JacksonXmlProperty(localName = "scoreName")指定xml文件中元素名称，而不用对象的字段名
   	 
        if ("user".equals(qName)) {
            user = new User();
            int id = Integer.valueOf(attributes.getValue("id"));//获取user元素的属性id的值
            user.setId(id);//将id写入user实例对象
        }

        switch (qName) {

            case "firstname":
                bfn = true;
                break;

            case "lastname":
                bln = true;
                break;

            case "occupation":
                boc = true;
                break;
        }
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {

        if (bfn) {//qName="firstname"触发
            user.setFirstName(new String(ch, start, length));
            bfn = false;
        }

        if (bln) {
            user.setLastName(new String(ch, start, length));
            bln = false;
        }

        if (boc) {
            user.setOccupation(new String(ch, start, length));
            boc = false;
        }
    }

    @Override
    public void endElement(String uri, String localName,String qName) throws SAXException {

        if ("user".equals(qName)) {
      	  //System.out.println(localName);
           users.add(user);
        }
    }

    public List<User> getUsers() {

        return users;
    }
    
}

